import { Base64 } from 'js-base64';
import type { UserInfo } from '/#/store';
import { defineStore } from 'pinia';
import { store } from '/@/store';
import { RoleEnum } from '/@/enums/roleEnum';
import { PageEnum } from '/@/enums/pageEnum';
import { ROLES_KEY, ACCESS_KEY, REFRESH_KEY, USER_INFO_KEY } from '/@/enums/cacheEnum';
import { getAuthCache, setAuthCache } from '/@/utils/auth';
import { GetUserInfoModel, LoginParams } from '/@/api/sys/model/userModel';
import { authApi } from '/@/api/sys/user';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { router } from '/@/router';
import { usePermissionStore } from '/@/store/modules/permission';
import { RouteRecordRaw } from 'vue-router';
import { PAGE_NOT_FOUND_ROUTE } from '/@/router/routes/basic';
import { h } from 'vue';

interface Token {
  token: string;
  exp: number;
}
interface UserState {
  userInfo: Nullable<UserInfo>;
  access?: Token;
  refresh?: Token;
  roleList: RoleEnum[];
  sessionTimeout?: boolean;
  lastUpdateTime: number;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    // user info
    userInfo: getAuthCache<UserInfo>(USER_INFO_KEY),
    // token
    access: getAuthCache<Token>(ACCESS_KEY),
    refresh: getAuthCache<Token>(REFRESH_KEY),
    // roleList
    roleList: getAuthCache<RoleEnum[]>(ROLES_KEY) || [],
    // Whether the login expired
    sessionTimeout: false,
    // Last fetch time
    lastUpdateTime: 0,
  }),
  getters: {
    getUserInfo(): UserInfo {
      return (this.userInfo as UserInfo) || {};
    },
    getAccessToken(): string {
      return this.access?.token || '';
    },
    getRefreshToken(): string {
      return this.refresh?.token || '';
    },
    getAccessExp(): number {
      return this.access?.exp || -1;
    },
    getRefreshExp(): number {
      return this.refresh?.exp || -1;
    },
    getRoleList(): RoleEnum[] {
      return this.roleList.length > 0 ? this.roleList : getAuthCache<RoleEnum[]>(ROLES_KEY);
    },
    getSessionTimeout(): boolean {
      return !!this.sessionTimeout;
    },
    getLastUpdateTime(): number {
      return this.lastUpdateTime;
    },
  },
  actions: {
    setAccessToken(info: string | undefined) {
      this.access = undefined;
      if (info) {
        const data = JSON.parse(Base64.decode(info.split('.')[1]));
        const token = { token: info, exp: data.exp };
        setAuthCache(ACCESS_KEY, token);
        this.access = token;
        this.setUserInfo(data);
      }
    },
    setRefreshToken(info: string | undefined) {
      this.refresh = undefined;
      if (info) {
        const data = JSON.parse(Base64.decode(info.split('.')[1]));
        const token = { token: info, exp: data.exp };
        setAuthCache(REFRESH_KEY, token);
        this.refresh = token;
      }
    },
    setRoleList(roleList: RoleEnum[]) {
      this.roleList = roleList;
      setAuthCache(ROLES_KEY, roleList);
    },
    setUserInfo(info: UserInfo | null) {
      this.userInfo = info;
      this.lastUpdateTime = new Date().getTime();
      setAuthCache(USER_INFO_KEY, info);
    },
    setSessionTimeout(flag: boolean) {
      this.sessionTimeout = flag;
    },
    resetState() {
      this.userInfo = null;
      this.access = undefined;
      this.refresh = undefined;
      this.roleList = [];
      this.sessionTimeout = false;
    },
    /**
     * @description: login
     */
    async login(
      params: LoginParams & {
        goHome?: boolean;
      },
    ): Promise<GetUserInfoModel | null> {
      try {
        const { goHome = true, ...loginParams } = params;
        const data = await authApi.login(loginParams);
        const { access, refresh } = data;
        // save token
        this.setAccessToken(access);
        this.setRefreshToken(refresh);
        return this.afterLoginAction(goHome);
      } catch (error) {
        return Promise.reject(error);
      }
    },
    // 刷新Token
    async refreshToken() {
      try {
        const { access, refresh } = await authApi.refreshToken({ refresh: this.getRefreshToken });
        // save access && refresh token
        this.setAccessToken(access);
        this.setRefreshToken(refresh);
        return Promise.resolve(this.getUserInfo);
      } catch (error) {
        await router.push({
          path: PageEnum.BASE_LOGIN,
          query: { redirect: router.currentRoute.value.fullPath },
        });
      }
    },
    async afterLoginAction(goHome?: boolean): Promise<UserInfo | null> {
      if (!this.getAccessToken) return null;
      const sessionTimeout = this.sessionTimeout;
      if (sessionTimeout) {
        this.setSessionTimeout(false);
      } else {
        const permissionStore = usePermissionStore();
        if (!permissionStore.isDynamicAddedRoute) {
          const routes = await permissionStore.buildRoutesAction();
          routes.forEach((route) => {
            router.addRoute(route as unknown as RouteRecordRaw);
          });
          router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
          permissionStore.setDynamicAddedRoute(true);
        }
        goHome && (await router.replace(PageEnum.BASE_HOME));
      }
      return this.getUserInfo;
    },
    /**
     * @description: logout
     */
    async logout() {
      this.resetState();
      setAuthCache(USER_INFO_KEY, undefined);
      setAuthCache(ACCESS_KEY, undefined);
      setAuthCache(REFRESH_KEY, undefined);
      setAuthCache(ROLES_KEY, undefined);
      router.push({
        path: PageEnum.BASE_LOGIN,
        query: { redirect: router.currentRoute.value.fullPath },
      });
    },

    /**
     * @description: Confirm before logging out
     */
    confirmLoginOut() {
      const { createConfirm } = useMessage();
      const { t } = useI18n();
      createConfirm({
        iconType: 'warning',
        title: () => h('span', t('sys.app.logoutTip')),
        content: () => h('span', t('sys.app.logoutMessage')),
        onOk: async () => {
          await this.logout();
        },
      });
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store);
}
